package com.qk.filter;

import com.qk.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String uri = request.getRequestURI();

        if(uri.contains("login")){
            filterChain.doFilter(request, response);
        }
        String jwt = request.getHeader("token");
        if(jwt == null || jwt.isEmpty()){
            log.info("token is null");
            response.setStatus(401);
            return;
        }
        try{
            JwtUtils.parseToken(jwt);
        }catch (Exception e){
            log.info("token is error");
            response.setStatus(401);
            return;
        }
        filterChain.doFilter(request, response);
    }
}
